/*
 * Copyright 2006 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.user.client.ui;

import java.util.Iterator;
import java.util.Vector;

/**
 * Abstract base class for panels that can contain multiple child widgets.
 */
public abstract class ComplexPanel extends Panel {

  private Vector children = new Vector();

  public boolean add(Widget w) {
    children.add(w);
    w.setParent(this);
    return true;
  }

  public void clear() {
    int count = getWidgetCount();
    for (int i = 0; i < count; i++) {
      remove(getWidget(0));
    }
  }

  public Widget getWidget(int index) {
    return (Widget) children.get(index);
  }

  public int getWidgetCount() {
    return children.size();
  }

  public int getWidgetIndex(Widget child) {
    return children.indexOf(child);
  }

  /**
   * Inserts a widget into the panel
   * 
   * @param w the widget to be inserted
   * @param beforeIndex the index before which it will be inserted
   * @return <code>true</code> on success (some panels place restrictions on
   *         how children may be added or inserted)
   */
  public boolean insert(Widget w, int beforeIndex) {
    if (beforeIndex > children.size())
      return false;

    children.insertElementAt(w, beforeIndex);
    w.setParent(this);
    return true;
  }

  public Iterator iterator() {
    return children.iterator();
  }

  public boolean remove(Widget w) {
    w.setParent(null);
    return children.remove(w);
  }
}
